package org.millioncall.yueyoga.admin.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.lang3.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.yueyoga.admin.dao.CheduleDAO;
import org.millioncall.yueyoga.admin.dao.CheduleDetailsDAO;
import org.millioncall.yueyoga.admin.dao.ReservationDAO;
import org.millioncall.yueyoga.admin.model.Chedule;
import org.millioncall.yueyoga.admin.model.CheduleDetails;
import org.millioncall.yueyoga.admin.model.ClassScheduleModel;
import org.millioncall.yueyoga.admin.model.Coach;
import org.millioncall.yueyoga.admin.model.Place;
import org.millioncall.yueyoga.admin.model.Reservation;
import org.millioncall.yueyoga.admin.service.CheduleService;
import org.springframework.stereotype.Service;

@Service
public class CheduleServiceImpl implements CheduleService {

	private CheduleDAO cheduleDAO;
	private CheduleDetailsDAO cheduleDetailsDAO;
	private ReservationDAO reservationDAO;

	public CheduleDAO getCheduleDAO() {
		return cheduleDAO;
	}

	public void setCheduleDAO(CheduleDAO cheduleDAO) {
		this.cheduleDAO = cheduleDAO;
	}

	public CheduleDetailsDAO getCheduleDetailsDAO() {
		return cheduleDetailsDAO;
	}

	public void setCheduleDetailsDAO(CheduleDetailsDAO cheduleDetailsDAO) {
		this.cheduleDetailsDAO = cheduleDetailsDAO;
	}

	public ReservationDAO getReservationDAO() {
		return reservationDAO;
	}

	public void setReservationDAO(ReservationDAO reservationDAO) {
		this.reservationDAO = reservationDAO;
	}

	@Override
	public int deleteByPrimaryKey(Integer id) {
		return this.cheduleDAO.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(Chedule record) {
		return this.cheduleDAO.insert(record);
	}

	@Override
	public int insertSelective(Chedule record) {
		return this.cheduleDAO.insertSelective(record);
	}

	@Override
	public Chedule selectByPrimaryKey(Integer id) {
		return this.cheduleDAO.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Chedule record) {
		return this.cheduleDAO.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Chedule record) {
		return this.cheduleDAO.updateByPrimaryKey(record);
	}

	@Override
	public List<Chedule> findBySubjectId(Integer subjectId) {
		return this.cheduleDAO.findBySubjectId(subjectId);
	}

	@Override
	public int updateOrInsert(Chedule record) {
		return this.cheduleDAO.updateOrInsert(record);
	}

	@Override
	public PaginatedList<Chedule> getCheduleInPage(int start, int pageSize,
			Map<String, Object> map) {
		return this.cheduleDAO.getCheduleInPage(start, pageSize, map);
	}

	@Override
	public boolean updateClassChedule(Map<String, Object> map) {
		return cheduleDAO.updateClassChedule(map) > 0;
	}

	@Override
	public Chedule getCheduleById(Integer cheduleId) {
		return this.cheduleDAO.getCheduleById(cheduleId);
	}

	DateTimeUtils dtu = DateTimeUtils.getInstance();

	@Override
	public boolean deleteScheduleByCdts(String kcxh, String scheduleId,
			String curDate) {
		Chedule c = null;
		if (StringUtils.isNotBlank(scheduleId)) {
			c = cheduleDAO.getCheduleById(Integer.valueOf(scheduleId));
		}
		CheduleDetails cDetails = null;
		if (StringUtils.isNotBlank(kcxh)) {
			cDetails = cheduleDetailsDAO.findCheduleDetailsByCdts(kcxh,
					scheduleId, curDate);
			cDetails.setIsReservation(3);
		}
		if (cDetails == null) {
			cDetails = new CheduleDetails();
			cDetails.setCheduleId(c.getId());
			// --原课程被删除,即新课程表覆盖原课程表数据
			cDetails.setIsReservation(3);
			cDetails.setCheduleTime(dtu.parse(curDate, "yyyy-MM-dd"));
			cDetails.setStarttime(c.getStarttime());
			cDetails.setEndtime(c.getEndtime());
			cDetails.setClassId(c.getClazz().getId());
		}
		if (cDetails.getId() == null) {
			reservationDAO.delReservationsByScheduleId(scheduleId);
			return cheduleDetailsDAO.addCheduleDetail(cDetails);
		}
		return cheduleDetailsDAO.updateCheduleDetails(cDetails) > 0;
	}

	@Override
	public boolean reservateSeat(String kcxh, String scheduleId, String curDate) {
		Integer scheId = null;
		if (StringUtils.isNotBlank(scheduleId)) {
			scheId = Integer.valueOf(scheduleId);
		}
		Reservation reservation = new Reservation();
		CheduleDetails cd = cheduleDetailsDAO.findCheduleDetailsByCdts(kcxh,
				scheduleId, curDate);
		reservation.setCreatetime(new Date());
		reservation.setIsEnable(false);
		if (StringUtils.isNotBlank(kcxh)) {
			reservation.setScheduleId(Integer.valueOf(kcxh));
		}
		boolean flag = false;
		int m = 0;
		
		boolean hasSwitchBook = false;//是否已开启预订
		if (cd != null) {
			//此处要判断是否已开启预订
			if(cd.getIsReservation().intValue() == 1 || cd.getState() == "接受预定"){//表示已开启预订
				hasSwitchBook = true;
				flag = true;
			}else {
				cd.setIsReservation(1);
				cd.setState("接受预定");
				flag = cheduleDetailsDAO.updateCheduleDetails(cd) > 0;
			}
		} else {
			cd = new CheduleDetails();
			Chedule c = this.cheduleDAO.getCheduleById(scheId);
			cd.setCheduleId(scheId);
			cd.setCheduleTime(dtu.parse(curDate, "yyyy-MM-dd"));
			cd.setIsReservation(1);
			cd.setStarttime(c.getStarttime());
			cd.setEndtime(c.getEndtime());
			Coach teacher = c.getTeacher();
			if (teacher != null) {
				cd.setTeacherId(teacher.getCoachId());
			}
			Coach assistant = c.getTeacher();
			if (assistant != null) {
				cd.setAssistantId(assistant.getCoachId());
			}
			Place place = c.getPlace();
			if (place != null) {
				cd.setPlaceId(place.getId());
			}
			cd.setSeatNumber(c.getSeatNumber());
			cd.setName(c.getName());
			cd.setClassId(c.getClazz().getId());
			cd.setState("接受预定");
			flag = cheduleDetailsDAO.addCheduleDetail(cd);
			reservation.setScheduleId(cd.getId());
		}
		
		if(flag){//预订状态保存成功
			if (cd.getSeatNumber() != null) {
				if(hasSwitchBook){//已开启预订，则不需要做添加席位操作
					return true;
				}else {
					for (int i = 0; i < cd.getSeatNumber(); i++) {
						int x = i + 1;
						reservation.setSeatNo(x < 10 ? ("0" + x) : (x + ""));
						m += reservationDAO.saveReservation(reservation);
					}
					return true;
				}
			}else {
				return false;
			}
		}else {
			return false;
		}
	}

	@Override
	public boolean addScheduleDetail(CheduleDetails sd) {
		return cheduleDetailsDAO.addCheduleDetail(sd);
	}

	@Override
	public PaginatedList<Chedule> findConsumptionSchedule(
			Map<String, Object> map, Integer start, Integer limit) {
		return this.cheduleDAO.findConsumptionSchedule(map, start, limit);
	}

	@Override
	public Chedule findConsumptionNewById(Map<String, Object> map) {
		return this.cheduleDAO.findConsumptionNewById(map);
	}

	@Override
	public List<ClassScheduleModel> findScheduleInfoList(String clazzId,
			String kcrq, String hallCode, String memberId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ClassScheduleModel> list = new ArrayList<ClassScheduleModel>();
		Calendar c = Calendar.getInstance();
		Calendar cdr = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		String dt = dtu.format(c.getTime(), "yyyy-MM-dd");
		kcrq = year + "-" + kcrq;
		// --今天日期
		Date jtrq = dtu.parse(dt, "yyyy-MM-dd");
		// --其他日期
		Date qtrq = dtu.parse(kcrq, "yyyy-MM-dd");
		cdr.setTime(qtrq);
		boolean rt = jtrq.getTime() >= qtrq.getTime();
		// --星期
		int week = cdr.get(Calendar.DAY_OF_WEEK) - 1;
		if (0 == week) {
			week = 7;
		}
		map.put("week", week);
		map.put("hallCode", hallCode);
		map.put("cheduleTime", kcrq);
		if (StringUtils.isNotBlank(memberId)) {
			map.put("memberId", memberId);
		}
		if (StringUtils.isNotBlank(clazzId)) {
			map.put("classId", clazzId);
		}
		List<ClassScheduleModel> oldList = cheduleDAO
				.findScheduleListByCdts(map);
		List<ClassScheduleModel> newList = cheduleDetailsDAO
				.findScheduleDetailListByCdts(map);

		if (oldList != null && !oldList.isEmpty()) {
			for (ClassScheduleModel cm : oldList) {
				String date = dtu.format(new Date(), "yyyy-MM-dd");
				// --拼接旧表时间字符串
				String oldt = date + " " + cm.getJssj();
				Date oldTime = dtu.parse(oldt, "yyyy-MM-dd HH:mm");
				if (rt && oldTime.getTime() <= c.getTime().getTime()) {
					cm.setYdzt("预定结束");
				} else {

				}
				cm.setKcrq(kcrq);
				cm.setCxrs("0");
				cm.setQxrs("0");
				list.add(cm);
			}
		}

		if (newList != null && !newList.isEmpty()) {
			for (int i = 0; i < newList.size(); i++) {
				ClassScheduleModel cm = newList.get(i);

				String newo = cm.getKcrq() + " " + cm.getJssj();
				Date newTime = dtu.parse(newo, "yyyy-MM-dd HH:mm");
				
				Calendar ca = Calendar.getInstance();
				ca.setTime(newTime);
				cm.setKcxq(String.valueOf(ca.get(Calendar.DAY_OF_WEEK)-1));
								
				if (rt && newTime.getTime() <= c.getTime().getTime()) {
					cm.setYdzt("预定结束");
				} else {
					cm.setYdzt("接受预定");
				}
				String hyrs = cm.getHyrs();
				String[] hyls = hyrs.split("/");
				if (hyls[0].equals(hyls[1]) && !"0".equals(hyls[0])) {
					cm.setYdzt("预定结束");
				}
				list.add(cm);
			}
		}
		Collections.sort(list, new BeanComparator<ClassScheduleModel>("kssj"));
		return list;
	}

	@Override
	public List<ClassScheduleModel> findNowScheduleInfoList(String clazzId,
			String organizationId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ClassScheduleModel> list = new ArrayList<ClassScheduleModel>();
		Calendar c = Calendar.getInstance();

		// --星期
		int week = c.get(Calendar.DAY_OF_WEEK) - 1;
		// map.put("classId", "0");
		String dt = DateTimeUtils.getInstance().format(c.getTime(),
				"yyyy-MM-dd HH:mm");
		String[] dts = dt.split(" ");
		String time = dts[1];
		String kcrq = dts[0];
		map.put("week", week);
		map.put("hallCode", organizationId);
		map.put("kcsj", time);
		map.put("cheduleTime", kcrq);
		if (StringUtils.isNotBlank(clazzId)) {
			map.put("classId", clazzId);
		}
		List<ClassScheduleModel> oldList = cheduleDAO
				.findScheduleListByCdts(map);
		List<ClassScheduleModel> newList = cheduleDetailsDAO
				.findScheduleDetailListByCdts(map);

		if (oldList != null && !oldList.isEmpty()) {
			for (ClassScheduleModel cm : oldList) {
				String date = dtu.format(new Date(), "yyyy-MM-dd");
				// --拼接旧表时间字符串
				String oldt = date + " " + cm.getJssj();
				Date oldTime = dtu.parse(oldt, "yyyy-MM-dd HH:mm");
				if (oldTime.getTime() <= c.getTime().getTime()) {
					cm.setYdzt("预定结束");
				}else {
					cm.setYdzt("未开启预定");
				}
				cm.setKcrq(kcrq);
				cm.setCxrs("0");
				cm.setQxrs("0");
				list.add(cm);
			}
		}

		if (newList != null && !newList.isEmpty()) {
			for (int i = 0; i < newList.size(); i++) {
				ClassScheduleModel cm = newList.get(i);
				String newo = cm.getKcrq() + " " + cm.getJssj();
				Date newTime = dtu.parse(newo, "yyyy-MM-dd HH:mm");
				if (newTime.getTime() <= c.getTime().getTime()) {
					cm.setYdzt("预定结束");
				}
				String hyrs = cm.getHyrs();
				String[] hyls = hyrs.split("/");
				if (hyls[0].equals(hyls[1]) && !"0".equals(hyls[0])) {
					cm.setYdzt("预定结束");
				}
				list.add(cm);
				cm = null;
			}
		}
		Collections.sort(list, new BeanComparator<ClassScheduleModel>("kssj"));
		return list;
	}

	@Override
	public List<ClassScheduleModel> findPersonScheduleList(String clazzId,
			String date, String memberId, String hallCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		date = year + "-" + date;
		map.put("cheduleTime", date);
		map.put("memberId", memberId);
		map.put("hallCode", hallCode);
		map.put("state", "否");
		if (StringUtils.isNotBlank(clazzId)) {
			map.put("classId", clazzId);
		}
		List<ClassScheduleModel> csm = cheduleDetailsDAO
				.findPersonScheduleListByCdts(map);
		if (csm == null) {
			return null;
		}
		for (ClassScheduleModel cm : csm) {
			cm.setYdzt("预定");
		}
		return csm;
	}

	@Override
	public List<ClassScheduleModel> findAttendScheduleList(String clazzId,
			String date, String memberId, String hallCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		date = year + "-" + date;
		map.put("cheduleTime", date);
		map.put("memberId", memberId);
		map.put("hallCode", hallCode);
		map.put("state", "是");
		if (StringUtils.isNotBlank(clazzId)) {
			map.put("classId", clazzId);
		}
		List<ClassScheduleModel> csm = cheduleDetailsDAO
				.findPersonScheduleListByCdts(map);
		return csm;
	}

	@Override
	public List<Chedule> findAllScheduleOneReserve(Map<String, Object> map) {
		return this.cheduleDAO.findAllScheduleOneReserve(map);
	}

	@Override
	public int updateScheduleReserve(Map<String, Object> map) {
		return this.cheduleDAO.updateScheduleReserve(map);
	}

	@Override
	public Set<String> findAllWeekClassIds(Date aDay) {
		Calendar can = Calendar.getInstance(Locale.CHINA);
		can.setTime(aDay);
		int week = can.get(Calendar.DAY_OF_WEEK) - 1;
		if (week == 0) {
			week = 7;
		}
		return this.cheduleDAO.findAllWeekClassIds(week, aDay);
	}

	@Override
	public Set<String> findAllDateClassIds(Date aDay) {
		return this.cheduleDAO.findAllDateClassIds(aDay);
	}
}
